#!/usr/bin/env python3
"""
Startup script for EmailQA API with MySQL database initialization
"""
import sys
import os
sys.path.append('src')

from src.interfaces.api import app

def main():
    """Main function to start the API server"""
    print("Starting EmailQA API with MySQL Database Support")
    print("=" * 50)
    
    try:
        # Check if MySQL connection is available
        from src.interfaces.api import mysql_connection
        
        print("Testing MySQL database connection...")
        if mysql_connection.test_connection():
            print("[OK] MySQL database connection successful")
            
            # Check if table exists
            if mysql_connection.table_exists('email_pending_task'):
                print("[OK] Email pending task table exists")
            else:
                print("[INFO] Email pending task table does not exist, will be created automatically")
            
        else:
            print("[WARNING] MySQL database connection failed")
            print("[INFO] API will start but email pending task functionality will be limited")
        
        print("\nStarting Flask API server...")
        print("API will be available at: http://localhost:5000")
        print("Health check: http://localhost:5000/api/health")
        print("Email pending task endpoint: http://localhost:5000/api/email_pending_task")
        print("\nPress Ctrl+C to stop the server")
        
        # Start the Flask application
        app.run(debug=True, host='0.0.0.0', port=5000)
        
    except KeyboardInterrupt:
        print("\n[INFO] Server stopped by user")
        sys.exit(0)
    except Exception as e:
        print(f"[ERROR] Failed to start server: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()